package com.kite.ossServer;

import android.webkit.JavascriptInterface;
import com.kite.ossServer.FileAble;
import org.json.JSONObject;

import java.io.File;

public class OSS {
    public rootNode root;

    public OSS(String filename) throws Exception {
        // 使用rootNode.initRoot()方法初始化
        String initResult = rootNode.initRoot(filename);
        // initResult是JSON字符串，不需要赋值给root
        // root将在需要时通过其他方式初始化或保持为null
        root = null; // 暂时设为null，需要时再初始化
    }

    // 初始化OSS实例的根节点
    @JavascriptInterface
    public String initializeRootNode(String filename) {
        try {
            if (filename == null || filename.trim().isEmpty()) {
                return createErrorResponse("文件名不能为空");
            }

            String initResult = rootNode.initRoot(filename);
            JSONObject initResponse = new JSONObject(initResult);

            if (initResponse.getBoolean("success")) {
                // 创建一个临时的rootNode来获取文件路径
                File tempFile = new File(initResponse.getString("filePath"));
                this.root = new rootNode(tempFile);

                JSONObject result = new JSONObject();
                result.put("success", true);
                result.put("message", "根节点初始化成功");
                result.put("filePath", tempFile.getAbsolutePath());

                return result.toString();
            } else {
                return createErrorResponse("初始化失败: " + initResponse.getString("error"));
            }
        } catch (Exception e) {
            return createErrorResponse("初始化根节点失败: " + e.getMessage());
        }
    }

    // 保存节点树
    @JavascriptInterface
    public String saveNodeTree() {
        try {
            if (this.root == null) {
                return createErrorResponse("OSS实例未初始化");
            }

            String saveText = this.root.NodeTree.toJSON();
            String writeResult = FileAble.writeTextToFile(this.root.getNTFill().getAbsolutePath(), saveText);
            JSONObject writeResponse = new JSONObject(writeResult);

            JSONObject result = new JSONObject();
            result.put("success", writeResponse.getBoolean("success"));
            result.put("message", writeResponse.getBoolean("success") ? "节点树保存成功" : "节点树保存失败");

            return result.toString();
        } catch (Exception e) {
            return createErrorResponse("保存节点树失败: " + e.getMessage());
        }
    }

    // 创建OSS实例 - 修复拼写错误
    @JavascriptInterface
    public static String createOSS(String db) {
        try {
            OSS oss = new OSS(db);

            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("message", "OSS实例创建成功");

            return result.toString();
        } catch (Exception e) {
            return createErrorResponse("OSS实例创建失败: " + e.getMessage());
        }
    }

    // 获取核心节点
    @JavascriptInterface
    public String getCoreNode() {
        try {
            if (this.root == null) {
                return createErrorResponse("OSS实例未初始化");
            }

            Node coreNode = this.root.NodeTree;

            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("nodeName", coreNode.getNodeN());
            result.put("tropCount", coreNode.TropLength());
            result.put("childCount", coreNode.nodeLength());

            return result.toString();
        } catch (Exception e) {
            return createErrorResponse("获取核心节点失败: " + e.getMessage());
        }
    }

    // 根据路径获取节点
    @JavascriptInterface
    public String getNodeByPath(String path) {
        try {
            if (path == null || path.trim().isEmpty()) {
                return createErrorResponse("路径不能为空");
            }

            if (this.root == null) {
                return createErrorResponse("OSS实例未初始化");
            }

            Node node = this.root.NodeTree.joinPath(path);

            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("nodeName", node.getNodeN());
            result.put("isValid", node.Exted());
            result.put("tropCount", node.TropLength());
            result.put("childCount", node.nodeLength());

            return result.toString();
        } catch (Exception e) {
            return createErrorResponse("获取节点失败: " + e.getMessage());
        }
    }

    // 检查OSS是否已初始化
    @JavascriptInterface
    public String isInitialized() {
        try {
            boolean initialized = (this.root != null && this.root.NodeTree != null);

            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("initialized", initialized);

            if (initialized) {
                result.put("filePath", this.root.getNTFill().getAbsolutePath());
                result.put("nodeCount", this.root.NodeTree.nodeLength());
                result.put("tropCount", this.root.NodeTree.TropLength());
            }

            return result.toString();
        } catch (Exception e) {
            return createErrorResponse("检查初始化状态失败: " + e.getMessage());
        }
    }

    // ============ 辅助方法 ============

    private static String createErrorResponse(String error) {
        try {
            JSONObject response = new JSONObject();
            response.put("success", false);
            response.put("error", error);
            response.put("timestamp", System.currentTimeMillis());
            return response.toString();
        } catch (Exception e) {
            return "{\"success\":false,\"error\":\"响应创建失败\"}";
        }
    }
}